import React, { useState, useEffect } from 'react';
import { useLocation, useNavigate, useParams } from 'react-router-dom';
import { Button, Card, Row, Col, Typography, Space, Tag, Spin } from 'antd';
import { ArrowLeftOutlined, PhoneOutlined, AppstoreOutlined } from '@ant-design/icons';
import { ApiService } from '../services/api';
import './ProductDetailPage.css';

const { Title, Paragraph } = Typography;

const ProductDetailPage = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const { id } = useParams();
  const { product: initialProduct } = location.state || {};
  
  const [product, setProduct] = useState(initialProduct);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  // 获取产品详情
  useEffect(() => {
    const fetchProductDetail = async () => {
      if (!id) {
        navigate('/');
        return;
      }

      try {
        setLoading(true);
        setError(null);
        
        const response = await ApiService.getProductDetail(id);
        
        if (response.code === '0000' && response.data) {
          const productData = {
            id: response.data.productId,
            title: response.data.productName,
            description: response.data.productSimDesc || '',
            image: response.data.picUrl,
            picUrl: response.data.picUrl,
            content: response.data.productContentBind || ''
          };
          setProduct(productData);
        } else {
          setError('获取产品详情失败');
        }
      } catch (err) {
        console.error('获取产品详情失败:', err);
        setError('网络请求失败');
      } finally {
        setLoading(false);
      }
    };
    
    // 总是通过API获取最新的产品详情，确保数据是最新的
    fetchProductDetail();
  }, [id, navigate]);

  // 如果没有产品数据，返回首页
  if (!product && !loading) {
    navigate('/');
    return null;
  }

  // 判断是否为真实图片URL还是emoji
  const isImageUrl = product?.image && (product.image.startsWith('http') || product.image.startsWith('data:'));

  const handleBack = () => {
    navigate(-1);
  };

  const handleContact = () => {
    // 可以跳转到联系页面或显示联系方式
    navigate('/contact');
  };

  const handleProducts = () => {
    // 跳转到产品中心页面
    navigate('/products');
  };

  if (loading) {
    return (
      <div className="product-detail-page">
        <div className="container">
          <div className="back-button">
            <Button 
              icon={<ArrowLeftOutlined />} 
              onClick={handleBack}
              size="large"
            >
              返回
            </Button>
          </div>
          <div className="loading-container">
            <Spin size="large" />
            <p>加载产品详情中...</p>
          </div>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="product-detail-page">
        <div className="container">
          <div className="back-button">
            <Button 
              icon={<ArrowLeftOutlined />} 
              onClick={handleBack}
              size="large"
            >
              返回
            </Button>
          </div>
          <div className="error-container">
            <p>{error}</p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="product-detail-page">
      <div className="container">
        {/* 返回按钮 */}
        <div className="back-button">
          <Button 
            icon={<ArrowLeftOutlined />} 
            onClick={handleBack}
            size="large"
          >
            返回
          </Button>
        </div>

        <Row gutter={[32, 32]}>
          {/* 产品图片 */}
          <Col xs={24} lg={12}>
            <Card className="product-image-card">
              <div className="product-image-container">
                {isImageUrl ? (
                  <img 
                    src={product.image} 
                    alt={product.title}
                    className="product-detail-image"
                    onError={(e) => {
                      e.target.style.display = 'none';
                      e.target.nextSibling.style.display = 'flex';
                    }}
                  />
                ) : null}
                <div 
                  className="product-detail-icon" 
                  style={{ display: isImageUrl ? 'none' : 'flex' }}
                >
                  {product.image}
                </div>
              </div>
            </Card>
          </Col>

          {/* 产品信息 */}
          <Col xs={24} lg={12}>
            <Card className="product-info-card">
              <Space direction="vertical" size="large" style={{ width: '100%' }}>
                <div>
                  <Title level={2} className="product-title">
                    {product.title}
                  </Title>
                  <Tag color="blue" className="product-tag">
                    产品详情
                  </Tag>
                </div>

                <div className="product-description">
                  <Title level={4}>产品简介</Title>
                  <Paragraph className="description-text">
                    {product.description || '暂无产品简介'}
                  </Paragraph>
                </div>

                <div className="product-actions">
                  <Space size="middle">
                    <Button 
                      type="primary" 
                      size="large"
                      icon={<PhoneOutlined />}
                      onClick={handleContact}
                    >
                      联系我们
                    </Button>
                    <Button 
                      size="large"
                      icon={<AppstoreOutlined />}
                      onClick={handleProducts}
                    >
                      产品中心
                    </Button>
                  </Space>
                </div>
              </Space>
            </Card>
          </Col>
        </Row>

        {/* 产品富文本详介 */}
        {product.content && (
          <Row style={{ marginTop: '32px' }}>
            <Col span={24}>
              <Card className="product-content-card">
                <Title level={3}>产品详情</Title>
                <div 
                  className="product-rich-content"
                  dangerouslySetInnerHTML={{ __html: product.content }}
                />
              </Card>
            </Col>
          </Row>
        )}
      </div>
    </div>
  );
};

export default ProductDetailPage;
